const { app, autoUpdater, dialog } = require("electron");
const isDev = require("electron-is-dev");

const updateService = {
  update: (updateInfo) => {
    console.log(`${app.getVersion()}`);
    if (isDev) {
      // 如果是开发环境那么不要更新
      // return;
    }
    const {
      mainWindow
    } = updateInfo;
    console.log("updateService.update");

    const server = "http://192.168.10.99:1337";
    //const url = `${server}/update/${process.platform}/${app.getVersion()}`;
    //const url = `${server}/update/${process.platform}/${app.getVersion()}`;
    //Request URL: http://192.168.10.99:1337/download/1.0.2/windows_32/electron-appdemo-1.0.0%20Setup.exe

    const url = `${server}/update/${process.platform}/${app.getVersion()}`;

    console.log(url);

    autoUpdater.setFeedURL({ url });

    autoUpdater.on('checking-for-available', (event,args) => {
      mainWindow.webContents.send('autoUpdater', {
        title: 'checking-for-available',
        event,
        args,
      });
    });

    autoUpdater.on('update-not-available',()=>{
      mainWindow.webContents.send('autoUpdater', {
        title: 'update-not-available',
        message: '当没有可用更新的时候触发'
      });
    });

    autoUpdater.on('update-available', () => {
      mainWindow.webContents.send('autoUpdater', {
        title: 'update-available',
        message: 'Emitted when there is an available update. The update is downloaded automatically'
      });
    });

     autoUpdater.on('before-quit-for-update', () => {
       mainWindow.webContents.send('autoUpdater', {
         title: 'before-quit-for-update',
         message: '此事件是在用户调用quitAndInstall()之后发出的。'
       });
     });

    autoUpdater.on("update-downloaded", (event, releaseNotes, releaseName) => {

      mainWindow.webContents.send('autoUpdater', {
        title: 'update-downloaded',
        releaseNotes,
        releaseName
      });

      const dialogOpts = {
        type: "info",
        buttons: ["现在重启", "稍后重启"],
        title: "应用程序更新",
        message: process.platform === "win32" ? releaseNotes : releaseName,
        detail: "一个新的版本应用程序已经被下载了，重启应用程序来应用更新。",
      };

      dialog.showMessageBox(dialogOpts).then((returnValue) => {
        if (returnValue.response === 0) {
          autoUpdater.quitAnd();
        }
      });
    });

    autoUpdater.on("error", (message) => {
      console.error("There was a problem updating the application");
      console.error(message);
      // dialog.showErrorBox("error", message)
       mainWindow.webContents.send('autoUpdater', {
         title:'error',
         message
       });
    });

    const intervalExe = () => {
      setInterval(() => {
        autoUpdater.checkForUpdates();
      }, 60000);
    };

    intervalExe();
  },
};

module.exports = updateService;
